package com.stone.oauth.client.filter;

import org.apache.oltu.oauth2.client.OAuthClient;
import org.apache.oltu.oauth2.client.URLConnectionClient;
import org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
import org.apache.oltu.oauth2.client.response.OAuthAccessTokenResponse;
import org.apache.oltu.oauth2.client.response.OAuthResourceResponse;
import org.apache.oltu.oauth2.common.OAuth;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.types.GrantType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>Created with IntelliJ IDEA. </p>
 * <p>User: Stony </p>
 * <p>Date: 2016/7/7 </p>
 * <p>Time: 15:20 </p>
 * <p>Version: 1.0 </p>
 */
public class AuthFilter implements Filter {
    private static final Logger logger = LoggerFactory.getLogger(AuthFilter.class);


    public static String clientId = "12345";
    public static String clientSecret = "12345";
    public static String accessTokenUrl = "http://localhost:8080/access_token";
    public static String resourceUrl = "http://localhost:8080/resource";
    public static String redirectUrl = "http://localhost:8081/auth";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("Enter");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        logger.info("Enter");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String code = request.getParameter(OAuth.OAUTH_CODE);

        OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());

        try {
            OAuthClientRequest accessTokenRequest = OAuthClientRequest
                    .tokenLocation(accessTokenUrl)
                    .setGrantType(GrantType.AUTHORIZATION_CODE)
                    .setClientId(clientId)
                    .setClientSecret(clientSecret)
                    .setCode(code)
                    .setRedirectURI(redirectUrl)
                    .buildQueryMessage();

            OAuthAccessTokenResponse oAuthResponse = oAuthClient.accessToken(accessTokenRequest, OAuth.HttpMethod.POST);
            String accessToken = oAuthResponse.getAccessToken();
            Long expiresIn = oAuthResponse.getExpiresIn();
            String refreshToken = oAuthResponse.getRefreshToken();
            logger.info("accessToken = {}, refreshToken = {}, expiresIn = {}", accessToken, refreshToken, expiresIn);


            OAuthClientRequest bearerClientRequest = new OAuthBearerClientRequest(resourceUrl).setAccessToken(accessToken).buildBodyMessage();
            //restfull 风格 path :  book/{id}
//            bearerClientRequest.setHeader(OAuth.HeaderType.CONTENT_TYPE, "multipart/form-data");
//            bearerClientRequest.setBody("id=200");
            OAuthResourceResponse resourceResponse = oAuthClient.resource(bearerClientRequest, OAuth.HttpMethod.POST, OAuthResourceResponse.class);
            String body = resourceResponse.getBody();
            logger.info("body = {}", body);
            response.getWriter().write(body);
        } catch (OAuthSystemException | OAuthProblemException e) {
            e.printStackTrace();
        }
        logger.info("-------------------------------------------------------------------------------------");
    }

    @Override
    public void destroy() {
        logger.info("Enter");
    }
}
